package offertest.test04;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ThreadSafeTimer {
    // 线程安全的任务存储
    private final ConcurrentHashMap<String, ScheduledFuture<?>> tasks = new ConcurrentHashMap<>();
    // 线程池，用于调度定时任务
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

    /**
     * 添加定时任务
     * @param taskId 任务ID，唯一标识
     * @param task 任务内容（Runnable）
     * @param delay 延迟时间（毫秒）
     * @param period 周期时间（毫秒），若为0则表示非周期任务
     */
    public void scheduleTask(String taskId, Runnable task, long delay, long period) {
        // 防止重复添加
        if (tasks.containsKey(taskId)) {
            throw new IllegalArgumentException("Task ID " + taskId + " already exists!");
        }

        // 调度任务
        ScheduledFuture<?> future;
        if (period > 0) {
            // 周期性任务
            future = scheduler.scheduleAtFixedRate(task, delay, period, TimeUnit.MILLISECONDS);
        } else {
            // 单次任务
            future = scheduler.schedule(task, delay, TimeUnit.MILLISECONDS);
        }

        // 存入任务
        tasks.put(taskId, future);
    }

    /**
     * 取消定时任务
     * @param taskId 任务ID
     * @return 是否取消成功
     */
    public boolean cancelTask(String taskId) {
        ScheduledFuture<?> future = tasks.remove(taskId);
        if (future != null) {
            // 取消任务，true表示中断正在执行的任务
            return future.cancel(true);
        }
        return false;
    }

    /**
     * 关闭定时器，释放资源
     */
    public void shutdown() {
        scheduler.shutdown();
        try {
            // 等待现有任务完成，最多等待10秒
            if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) {
                // 强制关闭
                scheduler.shutdownNow();
            }
        } catch (InterruptedException e) {
            scheduler.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    // 测试代码
    public static void main(String[] args) throws InterruptedException {
        ThreadSafeTimer timer = new ThreadSafeTimer();

        // 添加一个周期性任务，每2秒打印一次
        timer.scheduleTask("task1", () -> System.out.println("Task 1 running at " + System.currentTimeMillis()), 
                          1000, 2000);

        // 添加一个单次任务，3秒后执行
        timer.scheduleTask("task2", () -> System.out.println("Task 2 executed at " + System.currentTimeMillis()), 
                          3000, 0);

        // 等待5秒后取消task1
        Thread.sleep(5000);
        timer.cancelTask("task1");
        System.out.println("Task 1 canceled");

        // 再等3秒后关闭定时器
        Thread.sleep(3000);
        timer.shutdown();
        System.out.println("Timer shut down");
    }
}